package org.chen.mvc.protocol;


import org.chen.mvc.handler.GetRequestHandler;
import org.chen.mvc.handler.PostRequestHandler;
import org.chen.mvc.handler.RequestHandler;
import org.chen.mvc.http.HttpMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * @author Chen
 * @since 2023/6/6 17:43
 */
public class HttpServerHandler {

    private static final Map<String, RequestHandler> requestHandlerMap;

    static {
        requestHandlerMap = new HashMap<>();
        initHeader();
    }

    public static void handler(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            getRequestHandlerMap(req.getMethod()).handleRequest(req, resp);
        } catch (Exception e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "服务器出现异常");
            e.printStackTrace();
        }
    }

    public static RequestHandler getRequestHandlerMap(String method) {
        return requestHandlerMap.get(method);
    }

    private static void initHeader() {
        registerHandler(HttpMethod.GET.name(), new GetRequestHandler());
        registerHandler(HttpMethod.POST.name(), new PostRequestHandler());
        registerHandler(HttpMethod.DELETE.name(), new GetRequestHandler());
        registerHandler(HttpMethod.PUT.name(), new GetRequestHandler());
        registerHandler(HttpMethod.OPTIONS.name(), new GetRequestHandler());
        registerHandler(HttpMethod.HEAD.name(), new GetRequestHandler());
        registerHandler(HttpMethod.PATCH.name(), new GetRequestHandler());
        registerHandler(HttpMethod.TRACE.name(), new GetRequestHandler());
    }

    private static void registerHandler(String name, RequestHandler handler) {
        requestHandlerMap.put(name, handler);
    }


}
